package com.ruoyi.exam.controller;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.exam.domain.ExamUserOrder;
import com.ruoyi.exam.service.impl.ExamUserOrderServiceImpl;
import com.ruoyi.exam.websocket.PayWebSocket;
import com.ruoyi.pay.domain.PayOrder;
import com.ruoyi.pay.service.impl.PayOrderServiceImpl;
import com.ruoyi.system.service.impl.SysUserServiceImpl;

import jakarta.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;

@RestController
@RequestMapping("/exam/pay")
public class ExamPayOrderInfoController extends BaseController {

    @Autowired
    private ExamUserOrderServiceImpl examUserOrderService;

    @Autowired
    private SysUserServiceImpl userService;

    @Autowired
    private PayOrderServiceImpl payOrderService;

    @PostMapping("/notify")
    @Anonymous
    public AjaxResult payNotify(HttpServletRequest request) throws IOException {
        JSONObject jsonObject = JSONObject.from(request.getParameterMap());
        String orderNumber = jsonObject.getJSONArray("out_trade_no").getString(0);
        PayOrder order = payOrderService.selectPayOrderByOrderNumber(orderNumber);
        if (jsonObject.getJSONArray("trade_status").getString(0).equals("TRADE_SUCCESS")) {
            ExamUserOrder examUserOrder = new ExamUserOrder();
            if (PayOrder.AI_ORDER.equals(order.getOrderContent())) {
                examUserOrder.setOrderType(ExamUserOrder.AI_ANALYZE);
            } else if (PayOrder.ANALYZE.equals(order.getOrderContent())) {
                examUserOrder.setOrderType(ExamUserOrder.SINGLE_ANALYZE);
            }
            SysUser sysUser = userService.selectUserByUserName(order.getCreateBy());
            examUserOrder.setUserId(sysUser.getUserId());
            examUserOrder.setCreateBy(order.getCreateBy());
            examUserOrder.setOrderId(order.getOrderId());
            examUserOrder.setCreateTime(DateUtils.getNowDate());
            examUserOrderService.insertExamUserOrder(examUserOrder);
        }
        PayWebSocket.sendPayResult(orderNumber,
                JSONObject.from(AjaxResult.success(jsonObject.getJSONArray("trade_status").getString(0))));
        return success();
    }
}
